package cn.aticow.springboot.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class SimpleServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger log  = Logger.getLogger(SimpleServerHandler.class);
    public static List<Channel> channels = new ArrayList<>();
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        Channel inChannel=ctx.channel();
        if(channels.size()==0){//如果没有连接就进行连接就对了
            channels.add(inChannel);
            log.info("=== " + ctx.channel().remoteAddress() + " is active ===");
        }
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);

        if (bytes.length >= 13) {
            System.out.println(bytes[4]);
        }
        //手动回收，防止内存泄露
        ReferenceCountUtil.release(buf);
        //服务器用于些客户端的数据
        byte[] data = new byte[6];
        data[0] = 2;
        data[1] = 2;
        data[2] = 86;
        data[3] = 86;
        data[4] = 3;
        data[5] = 3;
        ByteBuf byteBuf = Unpooled.wrappedBuffer(data);
        //写并且刷新
        ctx.writeAndFlush(byteBuf);
    }
}
